<template>
  <div class="user-auth">
    <el-card class="auth-card" shadow="always">
      <template #header>
        <div class="card-header">
          <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
        </div>
      </template>

      <!-- 登录表单 -->
      <el-form 
        v-if="isLogin" 
        :model="loginForm" 
        :rules="loginRules" 
        ref="loginFormRef" 
        label-width="80px"
      >
        <el-form-item label="用户ID" prop="user_id">
          <el-input-number 
            v-model="loginForm.user_id" 
            :min="1" 
            placeholder="请输入用户ID"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form 
        v-else 
        :model="registerForm" 
        :rules="registerRules" 
        ref="registerFormRef" 
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleRegister" :loading="loading" style="width: 100%">
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 切换按钮 -->
      <div class="switch-mode">
        <el-button type="text" @click="toggleMode">
          {{ isLogin ? '还没有账号？去注册' : '已有账号？去登录' }}
        </el-button>
      </div>

      <!-- 当前用户信息 -->
      <div v-if="currentUser" class="current-user">
        <el-divider />
        <div class="user-info">
          <el-tag type="success" size="large">
            <el-icon><User /></el-icon>
            当前用户: {{ currentUser.username }} (ID: {{ currentUser.id }})
          </el-tag>
          <el-button type="danger" size="small" @click="handleLogout">
            退出登录
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import * as usersApi from '../api/users.js'

// 状态
const isLogin = ref(true)
const loading = ref(false)
const loginFormRef = ref(null)
const registerFormRef = ref(null)
const currentUser = ref(null)

// 登录表单
const loginForm = reactive({
  user_id: null
})

// 注册表单
const registerForm = reactive({
  username: '',
  email: ''
})

// 登录验证规则
const loginRules = {
  user_id: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', min: 1, message: '用户ID必须大于0', trigger: 'blur' }
  ]
}

// 注册验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 50, message: '用户名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      // 获取用户信息
      const user = await usersApi.getUser(loginForm.user_id)
      
      // 保存到 localStorage
      localStorage.setItem('currentUser', JSON.stringify(user))
      currentUser.value = user
      
      ElMessage.success(`欢迎回来，${user.username}！`)
      
      // 跳转到任务管理页面
      setTimeout(() => {
        window.location.href = '/tasks'
      }, 1000)
    } catch (error) {
      ElMessage.error('登录失败: ' + error.message)
    } finally {
      loading.value = false
    }
  })
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      // 创建用户
      const user = await usersApi.createUser(registerForm)
      
      // 保存到 localStorage
      localStorage.setItem('currentUser', JSON.stringify(user))
      currentUser.value = user
      
      ElMessage.success(`注册成功！欢迎，${user.username}！`)
      
      // 跳转到任务管理页面
      setTimeout(() => {
        window.location.href = '/tasks'
      }, 1000)
    } catch (error) {
      ElMessage.error('注册失败: ' + error.message)
    } finally {
      loading.value = false
    }
  })
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('currentUser')
  currentUser.value = null
  ElMessage.success('已退出登录')
}

// 初始化：检查是否已登录
onMounted(() => {
  const userStr = localStorage.getItem('currentUser')
  if (userStr) {
    try {
      currentUser.value = JSON.parse(userStr)
    } catch (error) {
      console.error('解析用户信息失败:', error)
      localStorage.removeItem('currentUser')
    }
  }
})
</script>

<style scoped>
.user-auth {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.auth-card {
  width: 100%;
  max-width: 450px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.switch-mode {
  text-align: center;
  margin-top: 20px;
}

.current-user {
  margin-top: 10px;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>
